import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import "./css/StatisticsHome.less";
import {DatePicker, Select, Spin} from "antd";
import {useTranslation} from "react-i18next";
import {AxiosGet} from "../../services/HttpService.tsx";
import GlobalIcon from "../../global/GlobalIcon.tsx";
import Echarts from "../../global/echarts/Echarts.tsx";
import CTable from "../../global/table/CTable.tsx";
import dayjs from "dayjs";
import Config from "../../Config.tsx";
import useStateRef from "../../customUse/useStateRef.tsx";

interface StatisticsHomeProps {
}

const StatisticsHome: FC<StatisticsHomeProps> = (props) => {

    const {t} = useTranslation();

    const defaultDateRef = useRef([dayjs().subtract(1, 'month'), dayjs()]);

    const [loading, setLoading] = useState(true),
        [summary, setSummary] = useState({}),
        [defaultDate, setDefaultDate] = useStateRef([dayjs().subtract(1, 'month'), dayjs()], defaultDateRef),
        [taskStatusOption, setTaskStatusOption] = useState([]),
        [deptTaskOption, setDeptTaskOption] = useState([]),
        [noticeClosedOption, setNoticeClosedOption] = useState([]),
        [supplierSign, setSupplierSign] = useState([]),
        [selectedSupplierSign, setSelectedSupplierSign] = useState([]);

    const loadSummary = useCallback(async () => {
        const {data = {}} = await AxiosGet("/sf-drs/notice/report/summary")
        setSummary(data)
    }, []);

    const loadTaskStatus = useCallback(async (params = {
        startDate: dayjs().subtract(1, 'month').format(Config.dateFormat.date),
        endDate: dayjs().format(Config.dateFormat.date),
    }) => {
        const {data = {}} = await AxiosGet("/sf-drs/notice/report/taskStatus", params)
        setTaskStatusOption({
            legend: {
                top: 30
            },
            tooltip: {
                trigger: 'item'
            },
            series: [
                {
                    name: t("status"),
                    type: 'pie',
                    radius: '50%',
                    center: ['50%', '60%'],
                    data: data.map(i => {
                        return {
                            value: i.count || 0,
                            name: i.status || ""
                        }
                    }),
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        })
    }, []);

    const loadDeptTasks = useCallback(async (params = {
        startDate: dayjs().subtract(1, 'month').format(Config.dateFormat.date),
        endDate: dayjs().format(Config.dateFormat.date),
    }) => {
        const {data = {}} = await AxiosGet("/sf-drs/notice/report/deptTasks", params),
            {deptNames = [], statusNames = []} = data;
        const series = [];
        statusNames.forEach((n, i) => {
            const values = []
            for (const k in data.data) {
                values.push(data.data[k][i])
            }
            series.push({
                data: values,
                stack: 'bar',
                type: 'bar',
                name: n
            })
        })
        setDeptTaskOption({
            legend: {
                top: 30
            },
            xAxis: {
                type: 'category',
                data: deptNames
            },
            yAxis: {
                type: 'value'
            },
            series
        })
    }, []);

    const loadNoticeClosed = useCallback(async () => {
        const {data = {}} = await AxiosGet("/sf-drs/notice/report/noticeClosed");
        setNoticeClosedOption({
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: data.months
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: data.data.map(i => (Number(i.completedRate))),
                    type: 'line',
                    areaStyle: {}
                }
            ]
        })
    }, []);

    const loadSupplierSign = useCallback(async () => {
        let data = [
            {id: "A", name: "供应商 A", time: 6},
            {id: "B", name: "供应商 B", time: 18.7},
            {id: "C", name: "供应商 C", time: 12.3},
            {id: "D", name: "供应商 D", time: 8.7},
            {id: "E", name: "供应商 E", time: 5.2},
            {id: "F", name: "供应商 F", time: 2.5},
            {id: "G", name: "供应商 G", time: 14.5},
            {id: "H", name: "供应商 H", time: 8.5},
            {id: "I", name: "供应商 I", time: 4.5},
            {id: "J", name: "供应商 J", time: 16.5},
            {id: "K", name: "供应商 K", time: 22.5},
        ]
        setSupplierSign(data)
        setSelectedSupplierSign([...data].splice(0, 8))
    }, []);

    const init = useCallback(async () => {
        setLoading(true);
        try {
            await Promise.all([
                loadSummary(),
                loadTaskStatus(),
                loadDeptTasks(),
                loadNoticeClosed(),
                loadSupplierSign()
            ]);
        } finally {
            setLoading(false);
        }
    }, [])

    useEffect(() => {
        init()
    }, []);

    const handleChangeDate = useCallback(async (values) => {
        const prevValues = defaultDateRef.current;
        if (dayjs(values[0]).isSame(prevValues[0]) && dayjs(values[1]).isSame(prevValues[1])) {
            return;
        }
        let params = {
            startDate: dayjs(values[0]).format(Config.dateFormat.date),
            endDate: dayjs(values[1]).format(Config.dateFormat.date),
        }
        setLoading(true);
        setDefaultDate(values);
        try {
            await Promise.all([
                loadTaskStatus(params),
                loadDeptTasks(params),
            ]);
        } finally {
            setLoading(false);
        }
        setLoading(false);
    }, []);

    const handleSupplerChange = useCallback(async (value, option) => {
        setSelectedSupplierSign(option)
    }, [])

    const renderStatisticsHomeHeader = useMemo(() => {
        const {
            notice = {total: 0, growthRate: 0},
            sign = {timelySignedRate: 0, growthRate: 0},
            outbound = {total: 0, growthRate: 0},
            supplierSign = {timelySignedRate: 0, growthRate: 0},
            user = {online: 0, total: 0}
        } = summary;
        return (
            <div className="sf_core_statistics_home_header">
                <div className="sf_core_statistics_home_header_item">
                    <div className="sf_core_statistics_home_header_item_title">
                        {t("noticeTotal")}
                    </div>
                    <div className="sf_core_statistics_home_header_item_content">
                        <div className="sf_core_statistics_home_header_item_content_text">
                            {notice.total}
                        </div>
                        <div
                            className={"sf_core_statistics_home_header_item_content_desc " + (Number(notice.growthRate) > 0 ? "item_rise" : "item_decline")}>
                            <GlobalIcon size={12} name={Number(notice.growthRate) > 0 ? "icon-rise" : "icon-decline"}/>
                            <span>{t("comparedYesterday", {growthRate: notice.growthRate})}</span>
                        </div>
                    </div>
                    <div className="sf_core_statistics_home_header_item_icon">
                        <GlobalIcon size={50} name="icon-tongzhiguanli"/>
                    </div>
                </div>
                <div className="sf_core_statistics_home_header_item">
                    <div className="sf_core_statistics_home_header_item_title">
                        {t("factoryNoticeTimelinessRate")}
                    </div>
                    <div className="sf_core_statistics_home_header_item_content">
                        <div className="sf_core_statistics_home_header_item_content_text">
                            {sign.timelySignedRate}%
                        </div>
                        <div
                            className={"sf_core_statistics_home_header_item_content_desc " + (Number(notice.growthRate) > 0 ? "item_rise" : "item_decline")}>
                            <GlobalIcon size={12} name={Number(notice.growthRate) > 0 ? "icon-rise" : "icon-decline"}/>
                            {t("comparedYesterday", {growthRate: sign.growthRate})}
                        </div>
                    </div>
                    <div className="sf_core_statistics_home_header_item_icon">
                        <GlobalIcon size={45} name="icon-10-wodeyiban"/>
                    </div>
                </div>
                <div className="sf_core_statistics_home_header_item">
                    <div className="sf_core_statistics_home_header_item_title">
                        {t("outboundNotificationImageFileTotal")}
                    </div>
                    <div className="sf_core_statistics_home_header_item_content">
                        <div className="sf_core_statistics_home_header_item_content_text">
                            {outbound.total}
                        </div>
                        <div
                            className={"sf_core_statistics_home_header_item_content_desc " + (Number(notice.growthRate) > 0 ? "item_rise" : "item_decline")}>
                            <GlobalIcon size={12} name={Number(notice.growthRate) > 0 ? "icon-rise" : "icon-decline"}/>
                            {t("comparedYesterday", {growthRate: outbound.growthRate})}
                        </div>
                    </div>
                    <div className="sf_core_statistics_home_header_item_icon">
                        <GlobalIcon size={45} name="icon-a-zu697"/>
                    </div>
                </div>
                <div className="sf_core_statistics_home_header_item">
                    <div className="sf_core_statistics_home_header_item_title">
                        {t("supplierSignTimelinessRate")}
                    </div>
                    <div className="sf_core_statistics_home_header_item_content">
                        <div className="sf_core_statistics_home_header_item_content_text">
                            {supplierSign.timelySignedRate}%
                        </div>
                        <div
                            className={"sf_core_statistics_home_header_item_content_desc " + (Number(notice.growthRate) > 0 ? "item_rise" : "item_decline")}>
                            <GlobalIcon size={12} name={Number(notice.growthRate) > 0 ? "icon-rise" : "icon-decline"}/>
                            {t("comparedYesterday", {growthRate: supplierSign.growthRate})}
                        </div>
                    </div>
                    <div className="sf_core_statistics_home_header_item_icon">
                        <GlobalIcon size={45} name="icon-bihuanshuai"/>
                    </div>
                </div>
                <div className="sf_core_statistics_home_header_item">
                    <div className="sf_core_statistics_home_header_item_title">
                        {t("currentNumberOnlineUsers")}
                    </div>
                    <div className="sf_core_statistics_home_header_item_content">
                        <div className="sf_core_statistics_home_header_item_content_text">
                            {user.online}
                        </div>
                        <div className="sf_core_statistics_home_header_item_content_desc">
                            {t("systemPeopleTotal", {total: user.total})}
                        </div>
                    </div>
                    <div className="sf_core_statistics_home_header_item_icon">
                        <GlobalIcon size={45} name="icon-dangzuzhijiagouyilanbiaoicon"/>
                    </div>
                </div>
            </div>
        )
    }, [summary])

    const renderStatisticsHomeDeptTaskEcharts = useMemo(() => {
        if (Object.keys(deptTaskOption).length === 0) return null
        return (<Echarts options={deptTaskOption} height={280}/>)
    }, [deptTaskOption]);

    const renderStatisticsHomeTaskStatusEcharts = useMemo(() => {
        if (Object.keys(taskStatusOption).length === 0) return null
        return (<Echarts options={taskStatusOption} height={300}/>)
    }, [taskStatusOption]);

    const renderStatisticsHomeNoticeClosedEcharts = useMemo(() => {
        if (Object.keys(noticeClosedOption).length === 0) return null
        return (<Echarts options={noticeClosedOption} height={300}/>)
    }, [noticeClosedOption]);

    const renderStatisticsHomeSupplierSign = useMemo(() => {
        return (
            <div className="sf_core_statistics_home_supplier_sign">
                <div className="sf_core_statistics_home_supplier_sign_left">
                    <div className="sf_core_statistics_home_supplier_sign_charts_title">
                        {t("factoryTasksStateDistribution")}
                    </div>
                    <div className="sf_core_statistics_home_supplier_sign_charts_search">
                        <DatePicker.RangePicker
                            value={defaultDate}
                            showTime={false}
                            allowClear={false}
                            size="small"
                            onChange={handleChangeDate}/>
                    </div>
                    <div className="sf_core_statistics_home_supplier_sign_charts_content">
                        {renderStatisticsHomeDeptTaskEcharts}
                    </div>
                </div>
                <div className="sf_core_statistics_home_supplier_sign_right">
                    <div className="sf_core_statistics_home_supplier_sign_right_header">
                        <div className="sf_core_statistics_home_supplier_sign_header_title">
                            {t("supplierSignTime")}
                        </div>
                        <div className="sf_core_statistics_home_supplier_sign_header_search">
                            <span>{t("supplierList")}:</span>
                            <Select
                                mode="tags"
                                size="small"
                                maxCount={8}
                                maxTagCount={1}
                                value={selectedSupplierSign.map(i => i.id)}
                                onChange={handleSupplerChange}
                                fieldNames={{label: "name", value: "id"}}
                                options={supplierSign}
                            />
                        </div>
                    </div>
                    <div className="sf_core_statistics_home_supplier_sign_right_content">
                        {selectedSupplierSign.map(i => {
                            return (
                                <div className="sf_core_statistics_home_supplier_sign_content_item">
                                    <div className="sf_core_statistics_home_supplier_sign_content_item_name">
                                        {i.name}
                                    </div>
                                    <div className="sf_core_statistics_home_supplier_sign_content_item_time">
                                        {i.time}
                                    </div>
                                    <div className="sf_core_statistics_home_supplier_sign_content_item_desc">
                                        {t("averageDeliveryTime")}
                                    </div>
                                </div>
                            )
                        })}
                    </div>
                </div>
            </div>
        )
    }, [defaultDate, supplierSign, selectedSupplierSign, deptTaskOption]);

    const renderStatisticsHomeEcharts = useMemo(() => {
        return (
            <div className="sf_core_statistics_home_charts">
                <div className="sf_core_statistics_home_charts_left">
                    <div className="sf_core_statistics_home_charts_title">
                        {t("entireFactoryNoticeTaskPercentage")}
                    </div>
                    <div className="sf_core_statistics_home_charts_left_search">
                        <DatePicker.RangePicker
                            value={defaultDate}
                            showTime={false}
                            allowClear={false}
                            size="small"
                            onChange={handleChangeDate}/>
                    </div>
                    <div className="sf_core_statistics_home_charts_content">
                        {renderStatisticsHomeTaskStatusEcharts}
                    </div>
                </div>
                <div className="sf_core_statistics_home_charts_right">
                    <div className="sf_core_statistics_home_charts_title">
                        {t("notificationLoopDistribution")}
                    </div>
                    <div className="sf_core_statistics_home_charts_content">
                        {renderStatisticsHomeNoticeClosedEcharts}
                    </div>
                </div>
            </div>
        )
    }, [defaultDate, taskStatusOption, noticeClosedOption]);

    const renderStatisticsHomeTable = useMemo(() => {
        return (
            <div className="sf_core_statistics_home_table">
                <div className="sf_core_statistics_home_table_left">
                    <div className="sf_core_statistics_home_table_title">
                        {t("taskList")}
                    </div>
                    <CTable
                        key="statisticsTaskTable"
                        view={"col_statistics_home_task_list"}
                        headerHeight={40}
                        height={300}
                        tableApi={{}}
                        rowKey="id"
                        isLazyData={true}
                        isShowHeader={false}
                    />
                </div>
                <div className="sf_core_statistics_home_table_right">
                    <div className="sf_core_statistics_home_table_title">
                        {t("outsourcedList")}
                    </div>
                    <CTable
                        key="statisticsOutsourcedTable"
                        view={"col_statistics_home_outsourced_list"}
                        headerHeight={40}
                        height={300}
                        tableApi={{}}
                        rowKey="id"
                        isLazyData={true}
                        isShowHeader={false}
                    />
                </div>
            </div>
        )
    }, [])

    const renderStatisticsHome = useMemo(() => {
        return (
            <Spin spinning={loading} wrapperClassName="sf_core_statistics_home">
                {renderStatisticsHomeHeader}
                {renderStatisticsHomeSupplierSign}
                {renderStatisticsHomeEcharts}
                {/*{renderStatisticsHomeTable}*/}
            </Spin>
        )
    }, [loading, defaultDate, summary, deptTaskOption, taskStatusOption, noticeClosedOption, supplierSign, selectedSupplierSign]);

    return (renderStatisticsHome);
};

export default React.memo(StatisticsHome);